package com.zynn.service.module.calculate.util;

import com.google.common.collect.Lists;
import com.zynn.service.module.calculate.bo.DegOneFrientWithWeight;
import lombok.extern.log4j.Log4j;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *@ClassName RecommandUtil
 *@Description TODO
 *@Author 刘猛
 *@Date 2018/10/17 11:00
 **/
@Log4j
public class RecommandUtil {

    /**
     * 快速去重
     * @param list
     * @param userId
     */
    public static void removeMyself(List<DegOneFrientWithWeight> list, Long userId) {
        List<DegOneFrientWithWeight> temp;
        temp = list.stream().filter( e -> !Objects.equals(e.getUserId(),userId)).collect(Collectors.toList());
        list.clear();
        list.addAll(temp);
    }

    /**
     * 当推荐用户中有相同用户分数不一样时取分数高的记录
     * @param list
     */
    public static void getHightestScoreRecommendUser(List<DegOneFrientWithWeight> list){
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        Map<Long, IntSummaryStatistics> collect = list.stream().collect(
                Collectors.groupingBy(DegOneFrientWithWeight::getUserId,
                        Collectors.summarizingInt(DegOneFrientWithWeight::getWeight)));
        if(Objects.nonNull(collect)){
            List<DegOneFrientWithWeight> tempList = Lists.newArrayList();
            IntSummaryStatistics statis;
            for(Map.Entry<Long,IntSummaryStatistics> entry : collect.entrySet()){
                statis = entry.getValue();
                tempList.add(new DegOneFrientWithWeight(entry.getKey(),statis.getMax()));
            }
            list.clear();
            list.addAll(tempList);
        }
    }

    /**
     * 判断es是否存在用户索引
     * @param userId
     * @return
     */
    public static boolean existsIndex(Long userId,RestHighLevelClient client){
        GetRequest getRequest = new GetRequest("user_friend_index", "_doc", userId.toString());
        boolean is = false;
        try {
            is = client.exists(getRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}
